#!/usr/bin/python
#coding:utf-8
#File Name    : monitor_backup_state.py
#Author       : moshan
#Mail         : shan.mo01@mljr.com
#Created Time : 2019-10-21 10:46:03
#Function     : 监控美利金融环境备份状态
#########################################################################
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email import encoders
import sys
import os
import pymysql
from datetime import *
#



def connect_mysql():
        return "",""
        mysql_host = "10.8.104"
        mysql_user = "user_dbmp"
        mysql_password = "77eHI"
        mysql_db = "dbmp_db"
        mysql_port = 3308
        t_today = datetime.now()
        t_today = str(t_today)[0:10]
        db = pymysql.connect(mysql_host, mysql_user, mysql_password, mysql_db, mysql_port, charset='utf8')
        cursor = db.cursor()
        cursor.execute("select (select count(*) from backup_info where backup_time = '" + t_today  + "') , (select count(*) from backup_project) limit 1;")
        data = cursor.fetchall()
        diff_data = []
        row_count = data[0]
        if row_count[0] != row_count[1]:
            cursor.execute("select name,concat(host,':',port) from backup_project where name not in (select project_name from backup_info where backup_time='" + t_today + "')")
            diff_data = cursor.fetchall()
        
        cursor.execute("select bi.project_name,bi.status, bi.size,bi.backup_time,bi.type,concat(bp.host,':',bp.port) host_port, bi.time_cost from backup_info bi join backup_project bp on bi.project_name = bp.name where bi.backup_time ='" + t_today + "'")
        data = cursor.fetchall()
        return data, diff_data

def send_mail(to_list, sub):
        me = mail_user 
        msg = MIMEMultipart()
        msg['Subject'] = sub
        msg['From'] = me
        msg['To'] = ",".join(to_list)
        data,diff_data = connect_mysql()
        time_now = str(datetime.now())
        time_now = time_now[0:19]
        table_info = []
        html = ""
        html_tmp = ""
        for row in data:
            print row
            data_tmp = row
            table_info_tmp = str(data_tmp[0].encode('utf-8'))
            backup_time = str(data_tmp[3] + " " + data_tmp[6])
            tmp_str = "<td><strong>" + table_info_tmp + "</strong></td>"
            table_info.append(tmp_str)
            if data_tmp[1] == 0:
                tmp_str = "<td><strong>成功</strong></td>"
                table_info.append(tmp_str)
                table_info.append(tmp_str)
            elif data_tmp[1] == 1:
                tmp_str = "<td><strong>成功</strong></td>"
                table_info.append(tmp_str)
                tmp_str = "<td style='background-color:#D2691E'><strong>失败</strong></td>"
                table_info.append(tmp_str)
            else:
                tmp_str = "<td style='background-color:#D2691E'><strong>失败</strong></td>"
                table_info.append(tmp_str)
                table_info.append(tmp_str)
            table_info_tmp = str(data_tmp[2].encode('utf-8'))
	    tmp_str = "<td><strong>" + table_info_tmp + "</strong></td>"
	    table_info.append(tmp_str)
	    tmp_str = "<td><strong>" + backup_time  + "</strong></td>"
            table_info.append(tmp_str)
            if data_tmp[4] == 'INCREMENTAL':
                tmp_str = "<td><strong>增备</strong></td>"
                table_info.append(tmp_str)
            elif data_tmp[4] == 'FULL':
                tmp_str = "<td><strong>全备</strong></td>"
                table_info.append(tmp_str)
            else:
                tmp_str = "<td><strong>未知</strong></td>"
                table_info.append(tmp_str)
            table_info_tmp = str(data_tmp[5].encode('utf-8'))
            tmp_str = "<td><strong>" + table_info_tmp + "</strong></td>"
            table_info.append(tmp_str)
            html_tmp += "<tr>" + table_info[0] + "\n" + table_info[1] + "\n" + table_info[2] + "\n" + table_info[3] + "\n" + table_info[4] + "\n" + table_info[5] + "\n" + table_info[6] + "</tr>\n"
            table_info = []

        diff_table_info = [] 
        for diff_row in diff_data:
            diff_data_tmp = diff_row
            diff_table_info_tmp = str(diff_data_tmp[0].encode('utf-8'))
            diff_tmp_str = "<td><strong>" + diff_table_info_tmp + "</strong></td>"
            diff_table_info.append(diff_tmp_str)
            diff_tmp_str = "<td style='background-color:#D2691E'><strong>失败</strong></td>"
            diff_table_info.append(diff_tmp_str)
            diff_table_info.append(diff_tmp_str)
            diff_tmp_str = "<td style='background-color:#D2691E'><strong>NULL</strong></td>"
            diff_table_info.append(diff_tmp_str)
            diff_table_info.append(diff_tmp_str)
            diff_table_info.append(diff_tmp_str)
            diff_table_info_tmp = str(diff_data_tmp[1].encode('utf-8'))
            diff_tmp_str = "<td><strong>" + diff_table_info_tmp + "</strong></td>"
            diff_table_info.append(diff_tmp_str)
            html_tmp += "<tr>" + diff_table_info[0] + "\n" + diff_table_info[1] + "\n" + diff_table_info[2] + "\n" + diff_table_info[3] + "\n" + diff_table_info[4] + "\n" + diff_table_info[5] + "\n" + diff_table_info[6] + "</tr>\n"
            diff_table_info = []
	html += """
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>备份状态信息展示</title>
	<body>
	<div id="container">
	  <p><span style="color:red;"><strong>美利金融-车环境-备份状态信息展示</strong></span></p>
	  <p>采集时间: """ + time_now + """</p>
	  <div id="content">
	   <table width="1000" border="2" bordercolor="black" cellspacing="2" style="font-family'宋体'; font-size50px;">
	  <tr>
	    <td><font color="#0000FF"><strong>业务名称</strong></font></td>
	    <td><font color="#0000FF"><strong>备份状态</strong></font></td>
	    <td><font color="#0000FF"><strong>转储状态</strong></font></td>
	    <td><font color="#0000FF"><strong>备份大小</strong></font></td>
	    <td><font color="#0000FF"><strong>备份时间</strong></font></td>
	    <td><font color="#0000FF"><strong>备份类型</strong></font></td>
	    <td><font color="#0000FF"><strong>IP地址:端口</strong></font></td>
	  </tr>""" + html_tmp + """
</table>
  </div>
</div>
</div>
</body>
</html>
        """
        html = "test"
       #构造html
#构造html
        context = MIMEText(html,_subtype='html',_charset='utf-8')  #解决乱码
        msg.attach(context) 
        try:
                send_smtp = smtplib.SMTP()
                send_smtp.connect(mail_host)
                send_smtp.login(mail_user, mail_pass)
                send_smtp.sendmail(me, to_list, msg.as_string())
                send_smtp.close()
                return True
        except Exception, e:
                print str(e)[1]
                return False
if __name__ == '__main__':
    # 设置服务器名称、用户名、密码以及邮件后缀
    mail_host = 'smtp.exmail.qq.com'
    mail_user = '1005155691@qq.com'
    mail_pass = 'moshan0821'
    #mailto_lists = sys.argv[1]
    #mailto_list = mailto_lists.split(',')   #发送多人
    #sub= sys.argv[2]
    mailto_list = ['907771586@qq.com',]
    #mailto_list = ['shan.mo01@mljr.com',]
    sub= "备份状态信息展示-车环境"
    time_now = str(datetime.now())
    time_now = time_now[0:19]
    if send_mail(mailto_list, sub):
            print "[", time_now, "] [ INFO ] Send mail succed!"
    else:
            print "Send mail failed!"
            print "[", time_now, "] [ ERROR ] Send mail failed!"

